import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken() || '',
    name: '',
    avatar: '',
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  // 存token
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  // SET_NAME: (state, name) => {
  //   state.name = name
  // },
  // SET_AVATAR: (state, avatar) => {
  //   state.avatar = avatar
  // },
  setUserInfo(state, userInfo) {
    console.log(userInfo)
    state.userInfo = userInfo
  },
  updateInfo(state, info) {
    state.userInfo = info
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  }
}

const actions = {
  // 发请求 登录
  async login(context, userInfo) {
    const res = await login(userInfo)
    // console.log(res)
    context.commit('SET_TOKEN', res.data.token)
  },

  // 发请求 获取用户信息
  async getInfo(context, payload) {
    const res = await getInfo()
    console.log(res)
    context.commit('setUserInfo', res.data.userinfo)
    return res.data.permission_menu_list
  },

  // user logout
  logout(context) {
    context.commit('removeToken')
    context.commit('updateInfo', {})
    resetRouter()
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  async getBtnList(context, payload) {
    const res = await getInfo()
    console.log(res)
    return res.data.permission_btn_list
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

